import axios from 'axios'

const BASE_URL = '/ammunition-supply'

/**
 * 获取弹药设施数据
 * @param {Object} params 查询参数
 * @returns {Promise<Object>} 返回弹药设施数据
 */
export function getFacilities(params) {
  return axios.get(`${BASE_URL}/facilities`, { params })
}

/**
 * 获取弹药供应网络数据
 * @param {Object} params 查询参数
 * @returns {Promise<Object>} 返回弹药供应网络数据
 */
export function getNetworkData(params) {
  return axios.get(`${BASE_URL}/network`, { params })
}

/**
 * 追踪弹药供应链
 * @param {string|number} facilityId 设施ID
 * @returns {Promise<Object>} 返回与指定设施相关的供应链数据
 */
export function traceSupplyChain(facilityId) {
  // 确保ID带有depot_前缀，但需要判断ID的类型和格式
  let formattedId = facilityId;
  
  // 如果ID是数字，直接添加前缀
  if (typeof facilityId === 'number') {
    formattedId = `depot_${facilityId}`;
  } 
  // 如果ID是字符串但不以depot_开头，添加前缀
  else if (typeof facilityId === 'string' && !facilityId.startsWith('depot_')) {
    // 如果字符串包含depot_但不在开头，提取数字部分
    if (facilityId.includes('depot_')) {
      const parts = facilityId.split('depot_');
      if (parts.length > 1) {
        formattedId = `depot_${parts[1]}`;
      } else {
        formattedId = `depot_${facilityId}`;
      }
    } else {
      formattedId = `depot_${facilityId}`;
    }
  }
  
  // 记录实际发送的请求URL，便于调试
  const requestUrl = `${BASE_URL}/trace/${formattedId}`;
  console.log('发送追踪请求:', requestUrl, '原始ID:', facilityId, '格式化后ID:', formattedId);
  
  return axios.get(requestUrl)
    .catch(err => {
      console.error('追踪请求失败:', err.response?.status, err.response?.data || err.message);
      throw err;
    });
}

/**
 * 获取初始数据
 * @returns {Promise<Object>} 返回初始化数据
 */
export function getInitialData() {
  return axios.get(`${BASE_URL}/initial`)
}

/**
 * 获取机场及关联弹药库数据
 * @param {Object} params 查询参数
 * @returns {Promise<Object>} 返回机场及关联弹药库数据
 */
export function getAirportsWithDepots(params) {
  return axios.get(`${BASE_URL}/airports`, { params });
} 